package com.ruoyi.api.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.*;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ConcurrentHashMap;

/**
 * sse推送
 */
//@RestController
//public class SseController {

//    @RequestMapping(value = "/sse")
//    @ResponseBody
//    public String getStreamDataImprove(HttpServletResponse httpServletResponse){
//        httpServletResponse.setContentType("text/event-stream");
//        httpServletResponse.setCharacterEncoding("utf-8");
//        String s = "";
//        while (true){
//            s = "data: " + new Date() + "\n\n";
//            try{
//                PrintWriter pw = httpServletResponse.getWriter();
//                Thread.sleep(1000L);
//                pw.write(s);
//                pw.flush();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
//}

@RestController
@CrossOrigin
public class SseController {

    private final Map<String, SseEmitter> sseEmitters = new ConcurrentHashMap<>();

    @GetMapping("/sse/{userId}")
    public SseEmitter connectSSE(@PathVariable String userId) {
        SseEmitter emitter = new SseEmitter(0L);
        sseEmitters.put(userId, emitter);
        emitter.onTimeout(() -> sseEmitters.remove(userId));
        emitter.onCompletion(() -> sseEmitters.remove(userId));
        return emitter;
    }

    /**
     * 给某个用户进行消息推送
     * @param userId
     * @param message
     */
    public void sendSSEMessage(String userId, String message) {
        SseEmitter emitter = sseEmitters.get(userId);
        if (emitter != null) {
            try {
                emitter.send(message, MediaType.TEXT_PLAIN);
            } catch (IOException e) {
                emitter.complete();
                sseEmitters.remove(userId);
            }
        }
    }

    /**
     * 给多个已连接用户推送消息
     * @param message
     */
    public void sendSSEMessages(String message) {
        sseEmitters.forEach((userId,sseEmitter) ->{
            try {
                sseEmitter.send(message, MediaType.TEXT_PLAIN);
            } catch (IOException e) {
                sseEmitter.complete();
                sseEmitters.remove(userId);
            }
        });
    }

    /**
     * 推送危险区域消息给所有人
     * @return
     */
    @GetMapping("/sse/sendMessage/dangerousAreaAdd")
    public AjaxResult sendMessageDangerous(){
        sendSSEMessages("2");
        return AjaxResult.success();
    }

    /**
     * 推送突发事件消息给所有人
     * @return
     */
    @GetMapping("/sse/sendMessage/emergercyEventAdd")
    public AjaxResult sendMessageEmergercy(){
        sendSSEMessages("1");
        return AjaxResult.success();
    }

    /**
     * 推送消息给管理员
     * @return
     */
    @GetMapping("/sse/sendMessageToAdmin")
    public AjaxResult sendMessageToAdmin(){
        sendSSEMessage("1","0");
        return AjaxResult.success();
    }
}
